package com.sx.wechat.controller;

import com.sx.core.dao.AllScoreMapper;
import com.sx.core.dao.ClazzMapper;
import com.sx.core.dao.DeviceMapper;
import com.sx.core.dao.InformationMapper;
import com.sx.core.dao.LaboratoryMapper;
import com.sx.core.dao.LessonMapper;
import com.sx.core.dao.OrderMapper;
import com.sx.core.dao.OrderRecStuMapper;
import com.sx.core.dao.PartScoreMapper;
import com.sx.core.model.AllScore;
import com.sx.core.model.Clazz;
import com.sx.core.model.Device;
import com.sx.core.model.Information;
import com.sx.core.model.Laboratory;
import com.sx.core.model.Lesson;
import com.sx.core.model.Order;
import com.sx.core.model.OrderRecStu;
import com.sx.core.model.PartScore;
import com.sx.core.utils.PropertyUtils;
import com.sx.core.utils.UUIDUtils;
import com.sx.core.vo.JsonReaderResponse;
import com.sx.core.vo.OrderContentVo;
import com.sx.wechat.service.OrderService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lihao on 16/12/21.
 */
@RestController
@RequestMapping("device")
public class RemoteDeviceController extends BaseController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    OrderService orderService;
    @Autowired
    DeviceMapper deviceMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderRecStuMapper orderRecStuMapper;
    @Autowired
    PartScoreMapper partScoreMapper;
    @Autowired
    AllScoreMapper allScoreMapper;
    @Autowired
    InformationMapper informationMapper;
    @Autowired
    LessonMapper lessonMapper;
    @Autowired
    LaboratoryMapper laboratoryMapper;
    @Autowired
    ClazzMapper clazzMapper;








    @Autowired
    ThreadPoolTaskExecutor executor;

    private String fileLocation= PropertyUtils.getProperty("file.location");

    /**
     * status 0待机，1正在实训，
     * @return
     */

    @RequestMapping(value = "lunxun")
    public JsonReaderResponse openid(String deviceId) {
        Device device=deviceMapper.get(Device.class,deviceId);

        String lessonid= device.getLessonid();
        String orderid= device.getOrderid();
        if(StringUtils.isEmpty(lessonid) || StringUtils.isEmpty(orderid)){
            Map map=new HashMap();
            map.put("status","0");
            map.put("stuid",null);
            map.put("stuname",null);
            map.put("clazzname",null);
            map.put("no",null);
            map.put("title",null);
            map.put("lessonname",null);
            map.put("lessonid",null);
            map.put("orderid",null);
            return new JsonReaderResponse().addExtra(map);
        }
        OrderContentVo order=orderMapper.getOrderContent(device.getOrderid());
        Map map=new HashMap();
        if(order!=null){
            Information information=informationMapper.get(Information.class,device.getStuid());
            Clazz clazz=clazzMapper.get(Clazz.class,information.getClassid());
            map.put("status",device.getStatus());
            map.put("stuid",information.getId());
            map.put("stuname",information.getName());
            map.put("clazzname",clazz!=null?clazz.getName():null);
            map.put("sno",information.getSno());
            map.put("no",order.getNo());
            map.put("title",order.getTitle());
            map.put("lessonname",order.getLessonname());
            map.put("lessonid",order.getLessonid());
            map.put("orderid",order.getId());
        }

        return new JsonReaderResponse().addExtra(map);





    }
    @RequestMapping(value = "uploadPartScore")
    public JsonReaderResponse uploadPartScore(
            String stuid,
            String orderid,
            String lessonid,
            String deviceid,
            String partid,
            String partname,
            Double score,
            @RequestParam(name = "file",required = false)MultipartFile file
    ) {

        String filepath=null;
        if(file!=null){
            String fileName = file.getOriginalFilename();
            File fileOnServer = null;
            String dir_str = FilenameUtils.normalize(fileLocation + File.separator+stuid+File.separator+deviceid);
            File dir=new File(dir_str);
            if(!dir.exists()){
                dir.mkdirs();
            }
            fileOnServer=new File(dir,fileName);
            try {
                byte[] bytes = file.getBytes();
                FileUtils.writeByteArrayToFile(fileOnServer,bytes);
            } catch (IOException e) {
                logger.error(e);
            }
            filepath=fileOnServer.getAbsolutePath();
        }
        try{
            OrderRecStu orderRecStu=orderRecStuMapper.selectByorderId(orderid, stuid);
            PartScore partScore=new PartScore();
            partScore.setId(UUIDUtils.generateUuid32());
            partScore.setStuid(stuid);
            partScore.setOrderid(orderid);
            partScore.setLessonid(lessonid);
            partScore.setDeviceid(deviceid);
            partScore.setPartid(partid);
            partScore.setPartname(partname);
            partScore.setScore(score);
            partScore.setFilepath(filepath);
            partScore.setCreatedate(new Date());
            partScore.setRsid(orderRecStu.getId());
            partScoreMapper.save(partScore);
        }catch (Exception e){

        }
       return new JsonReaderResponse();

    }
    @RequestMapping(value = "uploadAlltScore")
    public JsonReaderResponse uploadAlltScore( String stuid,
                                               String orderid,
                                               String lessonid,
                                               String deviceid,
                                               Double score,
                                               @RequestParam(name = "file",required = false)MultipartFile file) {

        List<Map<String,Object>> list=jdbcTemplate.queryForList("SELECT * FROM t_all_score WHERE stuid=? AND orderid=?",stuid,orderid);
        if(!list.isEmpty()){
            return new JsonReaderResponse();
        }
        String filepath=null;
        if(file!=null){
            String fileName = file.getOriginalFilename();
            File fileOnServer = null;
            String dir_str = FilenameUtils.normalize(fileLocation + File.separator+stuid+File.separator+deviceid);
            File dir=new File(dir_str);
            if(!dir.exists()){
                dir.mkdirs();
            }
            fileOnServer=new File(dir,fileName);
            try {
                byte[] bytes = file.getBytes();
                FileUtils.writeByteArrayToFile(fileOnServer,bytes);
            } catch (IOException e) {
                logger.error(e);
            }
            filepath=fileOnServer.getAbsolutePath();
        }

        OrderRecStu orderRecStu=orderRecStuMapper.selectByorderId(orderid, stuid);
//        orderRecStu.setStatus(1);
//        orderRecStu.setLastupdatedate(new Date());
//        orderRecStuMapper.update(orderRecStu);
        jdbcTemplate.update("UPDATE t_order_rec_stu SET status=?,lastupdatedate=? WHERE id=?",1,new Date(),orderRecStu.getId());

        AllScore allScore=new AllScore();
        allScore.setId(UUIDUtils.generateUuid32());
        allScore.setStuid(stuid);
        allScore.setOrderid(orderid);
        allScore.setLessonid(lessonid);
        allScore.setDeviceid(deviceid);
        allScore.setScore(score);
        allScore.setFilepath(filepath);
        allScore.setRsid(orderRecStu.getId());
        allScore.setCreatedate(new Date());
        allScoreMapper.save(allScore);


        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Information information=informationMapper.get(Information.class,stuid);
                    Lesson lesson=lessonMapper.get(Lesson.class,lessonid);
                    Order order=orderMapper.get(Order.class,orderid);
                    Laboratory laboratory=laboratoryMapper.get(Laboratory.class,order.getLabid());

                    orderService.pushScore(information,score,lesson.getId(),order.getId(),lesson.getName(),laboratory.getName(), DateFormatUtils.format(order.getStartdate(),"yyyy-MM-dd HH:mm"));
                }catch (Exception e){
                    logger.error("pushScore",e);
                }
            }
        });



        return new JsonReaderResponse();

    }
    @RequestMapping(value = "updateDevice")
    public JsonReaderResponse updateDevice(String deviceId) {
        jdbcTemplate.update("UPDATE t_device SET status=?,stuid=NULL,lessonid=NULL WHERE id=?","0",deviceId);

        return new JsonReaderResponse();

    }
    //todo
    @RequestMapping(value = "test")
    public JsonReaderResponse test(String deviceId) {
        jdbcTemplate.update("UPDATE t_device SET status=?,stuid=?,lessonid=?,orderid=? WHERE id=?","1","092e30b136ed4269b2389f3aa1d9ebd0","2699bddd2cd24472b56f7125466d9d1c","0e16c239190a4815bcd250ba19737af6",deviceId);

        return new JsonReaderResponse();

    }









}
